<?php

namespace App\Http\Controllers\Home;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB;
use Crypt;

class LoginController extends Controller
{
    //登录
    //
    public function login()
    {
    	return view('home.login.login');
    }

    //dologin
    public function dologin(Request $request)
    {
    	//验证
    	$this -> validate($request, [
    		'email' => 'required|email',
    		'password' => 'required'	
    		],[
    		'email.required' => '邮箱不能为空',
    		'email.email' => '非法邮箱',    		
    		'password.required' => '密码不能为空'
    		]);
    	//验证码验证
    	$scode = session('milkcaptcha');
    	$rcode = $request -> input('captcha');

    	if($scode != $rcode)
    	{
    		return back() -> with(['info' => '验证码不正确']);
    	}

    	//获取
    	$data = $request -> except('_token');

    	//查询
    	$res = DB::table('users') -> where('email', $data['email']) -> first();
        //判断
        if(!$res)
        {
            return back() -> with(['info' => '无此用户']);
        }

    	//解密
    	$password = Crypt::decrypt($res -> password);
    	
    	if($password == $data['password'])
    	{
    		
            DB::table('users') -> where('email', $data['email']) -> update(['ltime' => time()]);
            $res = DB::table('users') -> where('email', $data['email']) -> first();
            session(['master' => $res]);
    		return redirect('/home/user_set/');

    	}else
    	{
    		return back() -> with(['info' => '用户名或密码错误']);
    	}

    }

    //注册
    public function register()
    {
        return view('home.login.register');
    }

    public function doregister(Request $request)
    {
        // dd($request -> all());
        $data = $request -> except('_token','repassword');
        //验证
        $this->validate($request, [
        'username' => 'required|min:6|max:18',
        'password' => 'required',
        'repassword' => 'required|same:password',
        'email' => 'required|email'
    ],[
        'username.required' => '用户名不能为空',
        'username.min' => '用户名不能少于6位',
        'username.max' => '用户名不能大于18位',
        'password.required' => '密码不能为空',
        'repassword.required' => '确认密码不能为空',
        'repassword.same' => '两次密码不一致',
        'email.email' => '邮箱不合法',
        'email.required' => '邮箱不能为空',
    ]);
        //处理密码
        $data['password'] = Crypt::encrypt($data['password']);
        
        //处理token
        $data['token'] = str_random(50);
        //处理注册时间
        $data['ftime'] = time();        
        $data['ltime'] = time();        
        
        //执行添加
        $res = DB::table('users') -> insert($data);
        
        //判断
        if($res)
        {
            return redirect('/') -> with(['info' => '注册成功']);

        }else
        {
            return back() -> with(['info' => '注册失败']);
        }
    }
}
